const Flag = {
    // more(1) fun(2) seq(5)
    more: 1<<7,
    fun_cmd: 1<<5,
    fun_ssid: 2<<5,
    fun_pswd: 3<<5,
}
Uint8Array.prototype.copy = function(src, start, len) {
    start = start || 0
    len = len || src.length
    for (let i=0; i<len; i++) {
        this[i+start] = src[i] 
    }
}
function str2arr(str) {
    let buf = new Uint8Array(str.length)
    for (let i = 0; i < str.length; i++) {
        let c = str.charCodeAt(i)
        buf[i] = c
    }
    // return buf.buffer
    return buf
}
class BluTxPack {
    constructor(fun, str) {
		let arr = []
		let buf = str2arr(str)
        let seq = 0
		let mkpk = (len, fun, seq, more)=>{
			let sbuf = new Uint8Array(len+1)
			sbuf[0] = fun | (seq&0x31)
			if (more)  sbuf[0] |= Flag.more
			return sbuf
		}
		for (let len=buf.length; len>=20; len=buf.length) {
			let sbuf = mkpk(19, fun, seq++, true)
			sbuf.copy(buf, 1, len)
			buf = buf.subarray(19)
			arr.push(sbuf)
		}
		let sbuf = mkpk(buf.length, fun, seq++, false)
		sbuf.copy(buf, 1, buf.length)
		arr.push(sbuf)
		this.arr = arr
		this.pos = 0
        this.slot = []
    }
    peek() {
		return this.finish() ? null : this.arr[this.pos]
    }
    next() {
		this.pos++
	}
	finish() {
		return this.pos >= this.arr.length
	}
	reset() {
		return this.pos = 0
	}
	last() {
		return this.arr[this.arr.length-1]
	}
	seq(flag) {
		return flag & 0x1F
	}
	fun(flag) {
		return flag & (3<<5)
	}
}
class BluRxPack {
    constructor(data) {
        this.Reset()
        this.OnRecv(data)
    }

    Reset() {
        this.dat = null
    }

    OnRecv(data) {
        let ack = new Uint8Array(data)
        let dat = []
        if (ack.length>0) {
            let ack_num = ack[0]
            dat = ack.slice(1+ack_num)
        }
        this.dat = dat
    }
}


export { BluRxPack, BluTxPack, Flag }
